<template>
  <div class="rolesbox">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/users' }">用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row type="flex" class="theone">
        <el-col :span="24">
          <el-button type="primary" @click="dialogFormVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <el-table :data="tableData" border style="width: 100%  margin-top:10px">
        <el-table-column type="expand" width="50">
          <template slot-scope="props">
            <!-- <span>{{ props.row }}</span> -->
            <el-row
              v-for="(first, i) in props.row.children"
              :key="i"
              :span="24"
              type="flex"
            >
              <el-col :span="4" class="h-center" type="flex">
                <el-tag
                  closable
                  effect="dark"
                  @close="handleDeleteRights(first, props.row)"
                  >{{ first.authName }}</el-tag
                >
                <i class="el-icon-caret-right" v-if="first.children"></i>
              </el-col>

              <el-col :span="20">
                <el-row v-for="(second, j) in first.children" :key="j">
                  <el-col :span="4" class="h-center" type="flex">
                    <el-tag
                      closable
                      effect="dark"
                      type="success"
                      @close="handleDeleteRights(second, props.row)"
                      >{{ second.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right" v-if="second.children"></i>
                  </el-col>

                  <el-col :span="20">
                    <el-tag
                      closable
                      type="warning"
                      effect="dark"
                      v-for="(three, j) in second.children"
                      :key="j"
                      @close="handleDeleteRights(three, props.row)"
                      >{{ three.authName }}
                      <i class="el-icon-caret-right" v-if="three.children"></i>
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"> </el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >

            <el-button
              size="mini"
              type="warning"
              @click="allocatedLimits(scope.$index, scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
      <el-form :model="form" ref="form" :rules="rules">
        <el-form-item
          label="角色名称"
          prop="roleName"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="roleDesc"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改用户" :visible.sync="dialogFormVisibleEdit">
      <el-form :model="formEdit" ref="formEdit" :rules="rules">
        <el-form-item
          label="角色名称"
          prop="roleName"
          :label-width="formLabelWidth"
        >
          <el-input v-model="formEdit.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="roleDesc"
          :label-width="formLabelWidth"
        >
          <el-input v-model="formEdit.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="授权角色" :visible.sync="dialogFormVisibleEmpower">
      <div class="tree-container">
        <el-tree
          ref="tree"
          highlight-current
          default-expand-all
          :data="rightsData"
          show-checkbox
          node-key="id"
          :default-checked-keys="selectedRights"
          :props="defaultProps"
          @check-change="selectCheckEvent"
        >
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleEmpower = false">取 消</el-button>
        <el-button type="primary" @click="submitEmpower">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoles,
  getAddRoles,
  getDeleteRoles,
  getDeleteRolesRights,
  getQueryRolesById,
  getEditRoles,
  getRights,
  getRolesRights,
} from "../../api/index";
export default {
  data() {
    return {
      tableData: [],
      formLabelWidth: "200px",
      dialogFormVisible: false,
      form: {
        roleName: "",
        roleDesc: "",
      },
      dialogFormVisibleEdit: false,
      formEdit: {
        id: "",
        roleName: "",
        roleDesc: "",
      },
      dialogFormVisibleEmpower: false,
      rightsData: [],
      expandedKeys: [],
      checkedKeys: [],
      selectedRights: [],
      roleId: "",
      rids: "",
      defaultProps: {
        children: "children",
        label: "authName",
      },
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: false, message: "请输入角色描述", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      let { data: roles } = await getRoles("roles");
      console.log(roles);
      this.tableData = roles;
    },

    async addRoles() {
      let success = await this.$refs["form"].validate().catch(() => {});
      console.log(success);
      if (!success) return false;
      let {
        meta: { status },
      } = await getAddRoles(this.form);

      if (status == 201) {
        this.$message.success("添加用户成功");
        this.dialogFormVisible = false;
        this.getRolesList();
      }
    },

    async handleDelete(index, item) {
      console.log(index);
      console.log(item);
      let res = await this.$confirm("此操作将永久删除该文件，是否继续？", {
        confirmButtonText: "确实",
        cancelButtonText: "取消",
        type: "warning",
      }).catch(() => {});
      if (res != "confirm") return this.$message.info("取消删除");
      let {
        meta: { status, msg },
      } = await getDeleteRoles({ id: item.id });

      if (status == 200) {
        this.$message.success("删除成功");
        this.getRolesList();
      } else {
        this.$message.error("删除失败");
      }
    },

    async handleDeleteRights(index, item) {
      console.log(index.id);
      console.log(item);
      let res = await this.$confirm("此操作将永久删除该权限，是否继续？", {
        confirmButtonText: "确实",
        cancelButtonText: "取消",
        type: "warning",
      }).catch(() => {});
      if (res != "confirm") return this.$message.info("取消权限删除");
      let {
        data,
        meta: { status, msg },
      } = await getDeleteRolesRights({ roleId: item.id, rightId: index.id });

      if (status !== 200) return this.$message.error("删除权限失败");

      this.$message.success("删除权限成功");
      // this.getRolesList();
      item.children = data;
    },

    async handleEdit(index, item) {
      console.log(item.id);
      let {
        data,
        meta: { status },
      } = await getQueryRolesById({ id: item.id });
      if (status != 200) return this.$message.info("查询失败");
      this.formEdit = data;
      this.dialogFormVisibleEdit = true;
    },
    async editRoles() {
      let {
        meta: { status },
      } = await getEditRoles(this.formEdit);
      console.log(this.formEdit);
      console.log(status);
      if (status != 200) return this.$message.info("编辑失败");
      this.dialogFormVisibleEdit = false;
      this.getRolesList();
    },

    async allocatedLimits(i, scopedRow) {
      this.dialogFormVisibleEmpower = true;
      this.selectedRights = [];
      this.roleId = scopedRow.id;
      let {
        data,
        meta: { status },
      } = await getRights({ type: "tree" });
      if (status != 200) return this.$message.error("请求失败");

      this.rightsData = data;
      console.log(scopedRow);
      this.checkNodeId(scopedRow, this.selectedRights);
    },
    checkNodeId(scopedRowNode, selectedRightsArr) {
      if (!scopedRowNode.children) {
        return selectedRightsArr.push(scopedRowNode.id);
      }
      scopedRowNode.children.forEach((item) => {
        return this.checkNodeId(item, selectedRightsArr);
      });
    },
    async submitEmpower() {
      let {
        meta: { msg, status },
      } = await getRolesRights({ roleId: this.roleId, rids: this.rids });
      if (status != 200) return this.$message.error("授权权限失败");
      this.dialogFormVisibleEmpower = false;
      this.getRolesList();
    },
    selectCheckEvent() {
      let checkedKeys = this.$refs.tree.getCheckedKeys();
      let halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys();
      let arr = [...checkedKeys, ...halfCheckedKeys];
      console.log(arr);
      this.rids = arr.join();
    },
  },
};
</script>

<style scoped>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.box-card {
  width: 1158px;
}
.rolesbox {
  padding-left: 20px;
  width: 1158px;
}

.el-table {
  margin-top: 20px;
}

.el-pagination {
  margin: 20px auto;
  text-align: center;
}

.el-row--flex {
  align-items: center;
}

.h-center {
  display: flex;
  justify-content: center;
  align-items: center;
}
.el-row {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  border: 0.5px solid #efefef;
}

.el-tag--dark.el-tag--warning {
  background-color: #e6a23c;
  border-color: #e6a23c;
  color: #fff;
  margin: 5px 10px;
}

.theone {
  border: none;
}
</style>